package com.yunjinsuke.recharge.thread;

import com.yunjinsuke.recharge.entity.RechargeOrder;
import com.yunjinsuke.recharge.redis.RedisKeyUtil;
import com.yunjinsuke.recharge.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Random;


@Service
@Slf4j
public class AsyncService {

    @Value("${server.port}")
    private String serverPort;

    public static final Random random = new Random();

    private final RedisUtil redisUtil;

    public AsyncService(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    /**
     * 充值业务
     *
     * @param mchId            商户号
     * @param orderNumber      订单号
     * @param queryOrderNumber 查询订单号
     * @param mobile           手机号
     * @param amount           金额
     */
    @Async("asyncRechargeServiceExecutor")
    public void rechargeExecuteAsync(String mchId, String orderNumber, String queryOrderNumber, String mobile, Integer amount) {
        try {

            // TODO 模拟真实的话费充值业务
            Thread.sleep(50);

            String rechargeOrderStatus = RechargeOrder.SUCCEED;
            // 随机产生充值失败
            int randomNum = random.nextInt(1000);
            if (randomNum == 500) {
                rechargeOrderStatus = RechargeOrder.FAILED;
            }

            // 选改变状态
            redisUtil.set(RedisKeyUtil.queryOrderKey(queryOrderNumber), rechargeOrderStatus);

            // 创建订单
            RechargeOrder rechargeOrder = new RechargeOrder();
            rechargeOrder.setId(orderNumber);
            rechargeOrder.setMchId(mchId);
            rechargeOrder.setServerPort(serverPort);
            rechargeOrder.setMobile(mobile);
            rechargeOrder.setAmount(amount);
            rechargeOrder.setRechargeState(rechargeOrderStatus);
            // 根据均匀分散订单列表
            int num = random.nextInt(RedisKeyUtil.RECHARGE_ORDER_LIST_SIZE);
            redisUtil.lSet(RedisKeyUtil.rechargeOrderListKey(num), rechargeOrder);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}